<template>
  <div id="container">
    <div class="search positionAll" v-if="showInput">
      搜索区域：<MyInput v-model:value="keyWords" />
    </div>
    <div v-if="showInput">
      <el-button
        type="primary"
        class="positionAll addMarker"
        @click="addMarkerLisst"
        >点击添加marker</el-button
      >
      <el-button
        type="primary"
        class="positionAll adaptMarker"
        @click="adaptMarkerLisst"
        >自适应所有markers</el-button
      >
      <el-button type="primary" class="positionAll delMarker" @click="delMarker"
        >删除所有markers</el-button
      >
    </div>
    <div class="position positionAll" v-if="position.lng">
      当前点击的经纬度：{{ position.lng }},{{ position.lat }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from "vue";
import { shallowRef } from "@vue/reactivity";
import AMapLoader from "@amap/amap-jsapi-loader";
import { getMarkerLocal } from "../../api/map";
import { ElMessage } from "element-plus";
let Jsmap = shallowRef(null);
let MyJsAMap = reactive({
  Jsmap,
});
type Position = {
  lng: number;
  lat: number;
};
let markers = reactive([]);
const showInput = ref<boolean>(false);
//搜索的地区
const keyWords = ref("");
//检测输入框的改变,自动定位
watch(keyWords, (newValue) => {
  console.log("newValue", newValue);
  searchFound(MyJsAMap.Jsmap);
});
//根据搜索关键字自动跳转到页面
const searchFound = (AMap: any) => {
  AMap.plugin(["AMap.PlaceSearch"], () => {
    //构造地点查询类
    var placeSearch = new AMap.PlaceSearch({
      // pageSize: 5, // 单页显示结果条数
      // pageIndex: 1, // 页码
      city: "成都", // 兴趣点城市
      citylimit: false, //是否强制限制在设置的城市内搜索
      map: Jsmap, // 展现结果的地图实例
      // panel: "panel", // 结果列表将在此容器中进行展示。
      autoFitView: true, // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
      extensions: "base", //返回信息详略，默认为base（基本信息）
    });
    placeSearch.search(keyWords.value);
  });
};
//添加markers
const addMarkerLisst = async () => {
  let res = await getMarkerLocal();
  console.log("marker回来的res", res);
  addMarkers(res);
};
const addMarkers = (arry: any) => {
  let data = createMarker(arry);
  markers = data;
  Jsmap.add(data);
  ElMessage({
    showClose: true,
    message: "markers添加成功，您可以点击“自适应”按钮进行查看",
    type: "success",
  });
};
const createMarker = (arry: any) => {
  let showMarkers: any[] = [];
  arry.forEach((arr: any, index: number) => {
    let marker = adrMarker(MyJsAMap.Jsmap, arr, index);
    showMarkers.push(marker);
  });
  return showMarkers;
};
const adrMarker = (AMap: any, arr: any, index: number) => {
  let marker = new AMap.Marker({
    position: new AMap.LngLat(arr.lng, arr.lat), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
    title: arr.title,
    label: {
      content: `当前剩余车位数量：${arr.content}`,
      direction: "top",
    },
    //设置image的一些属性
    icon: new AMap.Icon({
      imageSize: new AMap.Size(25, 34),
      image: `https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-${
        index + 1
      }.png`,
    }),
    extData: arr.extData,
    anchor: "top-center",
  });
  //marker的点击事件
  const markerClick = (e: {
    target: { getExtData: () => { (): any; new (): any; lng: any; lat: any } };
  }) => {
    console.log("点击的marker", e);
    //获取自定义属性里面的数据
    Jsmap.setCenter([e.target.getExtData().lng, e.target.getExtData().lat]); //设置地图中心点
    // that.showMarkerListInfo = e.target.getExtData()//获取额外的marker里面是数据，高德api里面的
    // that.showMarkerInfo = true //让父组件的下方的详细信息展示出来
    ElMessage({
      showClose: true,
      message: "您点击了这个marker，可以进行下一步操作，比如跳转看详情等",
      type: "success",
    });
  };
  marker.on("click", markerClick);
  return marker;
};
//自适应所有markers
const adaptMarkerLisst = () => {
  Jsmap.setFitView(null, true, [60, 60, 60, 60], 20);
};
//删除地图上的markers
const delMarker = () => {
  Jsmap.remove(markers);
};
//点击地图的经纬度
const position = reactive<Position>({
  lng: 0,
  lat: 0,
});
onMounted(() => {
  initMap();
});
//初始化地图
const initMap = () => {
  AMapLoader.load({
    key: "0655f5d706c550cadbddcc7619443229", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: [""], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
  })
    .then((AMap) => {
      let map = new AMap.Map("container", {
        //设置地图容器id
        //设置地图容器id
        esizeEnable: true,
        viewMode: "2D", //是否为3D地图模式
        zoom: 14, //初始化地图级别
        plugins: ["AMap.MouseTool"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      });
      //地图加载完成
      map.on("complete", () => {
        Jsmap = map;
        MyJsAMap.Jsmap = AMap;
        showInput.value = true;
      });
      let markerList: any[] = [];
      const clickHandler = (e: any) => {
        position.lng = e.lnglat.getLng();
        position.lat = e.lnglat.getLat();
        map.remove(markerList);
        let marker = new AMap.Marker({
          icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
          position: [e.lnglat.getLng(), e.lnglat.getLat()],
          anchor: "bottom-center",
        });
        markerList.push(marker);
        marker.setMap(map);
      };
      //为地图添加点击事件
      map.on("click", clickHandler);
    })
    .catch((e) => {
      console.log(e);
    });
};
</script>
<style scoped lang="less">
#container {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 800px;
  position: relative;
  .positionAll {
    position: absolute;
    z-index: 9;
  }
  .position {
    top: 0;
    right: 0;
  }
  .search {
    top: 0;
    left: 0;
    margin-top: 20px;
  }
  .addMarker {
    left: 0;
    top: 80px;
  }
  .adaptMarker {
    left: 0;
    top: 120px;
    margin-left: 0 !important;
  }
  .delMarker {
    left: 0;
    top: 160px;
    margin-left: 0 !important;
  }
}
</style>
